<template>
  <div class="base-container" id="main">
    <t-steps :current="activeForm" status="process" :onChange="onCurChanged">
      <t-step-item title="基本信息" :content="isSubmit('step0')"></t-step-item>
      <t-step-item title="实施背景及必要性" :content="isSubmit('step1')"></t-step-item>
      <t-step-item title="依托工程（项目）概述" :content="isSubmit('step2')"></t-step-item>
      <t-step-item title="申报单位的前期工作和科研基础" :content="isSubmit('step3')"></t-step-item>
      <t-step-item title="科技示范工程的主要内容、示范规模、进度安排和组织实施方案" :content="isSubmit('step4')"></t-step-item>
      <t-step-item title="推广技术的主要内容与规模" :content="isSubmit('step5')"></t-step-item>
      <t-step-item title="主要目标和成果形式" :content="isSubmit('step6')"></t-step-item>
      <t-step-item title="单位信息" :content="isSubmit('step7')"></t-step-item>
      <t-step-item title="附件信息" :content="isSubmit('step8')"></t-step-item>
    </t-steps>
    <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
    </t-loading>
    <div class="edit-content">
      <!-- 基本信息 -->
      <t-form ref="form" class="step-form" :colon="true" v-if="activeForm === 0" :data="formData0" @submit="onSubmit0"
        :rules="rules0" labelWidth="180px">
        <t-row style="align-items: stretch;" :gutter="14">
          <t-col :span="12">
            <t-card class="step-card" size="small" title="基本信息">
              <t-row style="row-gap:24px">
                <t-col :span="6">
                  <t-form-item label="科技示范工程名称" name="projectName">
                    <t-input clearable style="width: 390px" v-model="formData0.projectName"></t-input>
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item label="申报日期" name="declareDate">
                    <t-date-picker clearable style="width: 390px" v-model="formData0.declareDate"></t-date-picker>
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item label="投入经费" name="adviceFunding">
                    <t-input-adornment append="万元">
                      <t-input-number :decimal-places="2"
                        @keyup="() => { if (formData0.adviceFunding) { formData0.adviceFunding = Number((formData0.adviceFunding || 0).toString().match(/^\d+(?:\.\d{0,2})?/)) } }"
                        :allowInputOverLimit="false" clearable style="width: calc(390px - 45px)"
                        v-model="formData0.adviceFunding" theme="normal" :min="0"></t-input-number>
                    </t-input-adornment>
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item label="主管单位" name="manageDeptId">
                    <t-tree-select clearable filterable style="width: 390px" :treeProps="{ keys: { value: 'id' } }"
                      @change="(val, content) => { formData0.manageDeptName = content.node.data.label }"
                      v-model="formData0.manageDeptId" :data="deptMenuOptions" placeholder="选择工作单位"></t-tree-select>
                  </t-form-item>
                </t-col>

                <t-col :span="6">
                  <t-form-item label="项目开始日期" name="startDate">
                    <t-date-picker clearable style="width: 390px" v-model="formData0.startDate"></t-date-picker>
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item label="项目结束日期" name="endDate">
                    <t-date-picker clearable style="width: 390px" v-model="formData0.endDate"></t-date-picker>
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item help="手输支持自定义创建" label="关键词" name="keyWordList">
                    <t-select v-model="formData0.keyWordList" creatable filterable multiple placeholder="手输支持自定义创建"
                      :options="dict.type.kjsf_key_word" style="width: 390px;" @create="createKeyWordOptions">
                    </t-select>
                  </t-form-item>
                </t-col>
              </t-row>
            </t-card>
          </t-col>
        </t-row>
        <!-- 项目负责人信息开始 -->
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12" style="margin-top:15px">
            <t-card class="step-card" size="small" title="科技示范工程负责人">
              <t-row>
                <t-col :span="6">
                  <t-form-item label="姓名" name="projectLeader.name">
                    <t-select v-model="formData0.projectLeader.name" creatable filterable @change="onLeaderNameChange"
                      placeholder="请输入姓名" :loading="leaderLoading" @search="remoteProjectLeaderMethod"
                      :options="projectLeaderOptions" @create="createProjectLeaderOptions" style="width: 390px" />
                    <!-- <t-input style="width: 390px"  placeholder="请输入姓名" clearable
                             v-model="formData0.projectLeader.name"
                    ></t-input> -->
                  </t-form-item>
                  <t-form-item label="性别" name="projectLeader.sex">
                    <t-select style="width: 390px" placeholder="请选择性别" :options="dict.type.sys_user_sex"
                      v-model="formData0.projectLeader.sex">
                    </t-select>
                  </t-form-item>
                  <t-form-item label="身份证号" name="projectLeader.idCard">
                    <t-input style="width: 390px" placeholder="请输入身份证号" clearable
                      v-model="formData0.projectLeader.idCard"></t-input>
                    <!-- <t-button @click="onOldUser" v-if="oldUser"
                              variant="text" class="t-button-link">
                      <t-icon name="info-circle" slot="icon"/>
                      已存在点击复填
                    </t-button> -->
                  </t-form-item>

                  <t-form-item label="出生年月" name="projectLeader.birthDate">
                    <t-date-picker placeholder="请选择生日" mode="month" v-model="formData0.projectLeader.birthDate"
                      :disable-date="{ after: dayjs().endOf('month').add(-18, 'year').format() }"
                      style="width: 390px"></t-date-picker>
                  </t-form-item>

                  <t-form-item label="工作单位" name="projectLeader.departmentId">
                    <t-tree-select clearable filterable style="width: 390px" :treeProps="{ keys: { value: 'id' } }"
                      v-model="formData0.projectLeader.departmentId" :data="deptMenuOptions"
                      placeholder="选择工作单位"></t-tree-select>
                  </t-form-item>
                  <t-form-item label="联系电话" name="projectLeader.phone">
                    <t-input style="width: 390px" placeholder="请输入手机号码" clearable
                      v-model="formData0.projectLeader.phone"></t-input>
                  </t-form-item>
                  <t-form-item label="通讯地址" name="projectLeader.address">
                    <t-input style="width: 390px" clearable v-model="formData0.projectLeader.address"></t-input>
                  </t-form-item>
                  <t-form-item label="电子信箱" name="projectLeader.email">
                    <t-input style="width: 390px" clearable v-model="formData0.projectLeader.email"></t-input>
                  </t-form-item>
                  <t-form-item label="邮编" name="projectLeader.postCode">
                    <t-input style="width: 390px" clearable v-model="formData0.projectLeader.postCode"></t-input>
                  </t-form-item>
                  <t-form-item label="毕业院校" name="projectLeader.school">
                    <t-input style="width: 390px" clearable v-model="formData0.projectLeader.school"></t-input>
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item label="学历" name="projectLeader.education">
                    <t-select style="width: 390px" v-model="formData0.projectLeader.education" clearable
                      placeholder="请选择学历" :options="dict.type.education">
                    </t-select>
                  </t-form-item>
                  <t-form-item label="学位" name="projectLeader.degree">
                    <t-select style="width: 390px" v-model="formData0.projectLeader.degree" clearable
                      placeholder="请选择学位" :options="dict.type.degree">
                    </t-select>
                  </t-form-item>
                  <t-form-item label="所学专业" name="projectLeader.majorName">
                    <t-input style="width: 390px" clearable v-model="formData0.projectLeader.majorName"></t-input>
                  </t-form-item>
                  <t-form-item label="现从事专业" name="projectLeader.majorNowName">
                    <t-input style="width: 390px" clearable v-model="formData0.projectLeader.majorNowName"></t-input>
                  </t-form-item>
                  <t-form-item label="职务" name="projectLeader.duty">
                    <t-input style="width: 390px" clearable v-model="formData0.projectLeader.duty"></t-input>
                  </t-form-item>
                  <t-form-item label="技术职称" name="projectLeader.profTitId">
                    <t-tree-select clearable @change="onProfTitIdChange" filterable style="width: 390px"
                      :treeProps="{ keys: { value: 'id', label: 'name' }, valueMode: 'onlyLeaf' }"
                      v-model="formData0.projectLeader.profTitId" :data="profTitOptions"
                      placeholder="技术职称"></t-tree-select>
                    <!--                    <t-input style="width: 390px" clearable v-model="formData0.projectLeader.profTitId"-->
                    <!--                    ></t-input>-->
                  </t-form-item>
                  <t-form-item label="职称" name="projectLeader.profTit">
                    <t-select disabled style="width: 390px" v-model="formData0.projectLeader.profTit" clearable
                      placeholder="请选择职称" :options="dict.type.prof_tit">
                    </t-select>
                  </t-form-item>
                  <t-form-item label="在本项目中承担的任务" name="projectLeader.task">
                    <t-textarea style="width: 390px" clearable :autosize="{ minRows: 3 }"
                      v-model="formData0.projectLeader.task" placeholder="请输入内容" />
                  </t-form-item>
                </t-col>
              </t-row>
            </t-card>
          </t-col>
        </t-row>
        <t-row style="align-items: stretch" :gutter="14">

          <!-- 项目联系人 -->
          <t-col :span="6">
            <t-card class="step-card" size="small" title="项目联系人">
              <t-form-item label="姓名" name="projectLinker.name">
                <t-select v-model="formData0.projectLinker.name" creatable filterable @change="onLinkerNameChange"
                  placeholder="请输入姓名" :loading="linkerLoading" @search="remoteProjectLinkerMethod"
                  :options="projectLinkerOptions" @create="createProjectLinkerOptions" style="width: 390px" />
                <!-- <t-input style="width: 390px" placeholder="请输入姓名" clearable
                         v-model="formData0.projectLinker.name"></t-input> -->
              </t-form-item>
              <t-form-item label="联系电话" name="projectLinker.phone">
                <t-input style="width: 390px" placeholder="请输入手机号码" clearable
                  v-model="formData0.projectLinker.phone"></t-input>
              </t-form-item>
              <t-form-item label="通信地址" name="projectLinker.address">
                <t-input style="width: 390px" clearable v-model="formData0.projectLinker.address"></t-input>
              </t-form-item>
              <t-form-item label="电子信箱" name="projectLinker.email">
                <t-input style="width: 390px" clearable v-model="formData0.projectLinker.email"></t-input>
              </t-form-item>
              <t-form-item label="邮编" name="projectLinker.postCode">
                <t-input style="width: 390px" clearable v-model="formData0.projectLinker.postCode"></t-input>
              </t-form-item>
            </t-card>
          </t-col>
          <!-- 主管部门联系人 -->
          <t-col :span="6">
            <t-card class="step-card" size="small" title="主管部门联系人">
              <t-form-item label="姓名" name="manageDeptLinker.name">
                <t-select v-model="formData0.manageDeptLinker.name" creatable filterable @change="onLinkerNameChange2"
                  placeholder="请输入姓名" :loading="linkerLoading2" @search="remoteProjectLinkerMethod2"
                  :options="projectLinkerOptions2" @create="createProjectLinkerOptions2" style="width: 390px" />
                <!-- <t-input style="width: 390px" placeholder="请输入姓名" clearable
                         v-model="formData0.projectLinker.name"></t-input> -->
              </t-form-item>
              <t-form-item label="联系电话" name="manageDeptLinker.phone">
                <t-input style="width: 390px" placeholder="请输入手机号码" clearable
                  v-model="formData0.manageDeptLinker.phone"></t-input>
              </t-form-item>
              <t-form-item label="通信地址" name="manageDeptLinker.address">
                <t-input style="width: 390px" clearable v-model="formData0.manageDeptLinker.address"></t-input>
              </t-form-item>
              <t-form-item label="电子信箱" name="manageDeptLinker.email">
                <t-input style="width: 390px" clearable v-model="formData0.manageDeptLinker.email"></t-input>
              </t-form-item>
              <t-form-item label="邮编" name="manageDeptLinker.postCode">
                <t-input style="width: 390px" clearable v-model="formData0.manageDeptLinker.postCode"></t-input>
              </t-form-item>
            </t-card>
          </t-col>
        </t-row>

        <t-row style="text-align: center">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" type="submit">下一步</t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
      <!-- 新增实施背景及必要性 -->
      <t-form ref="form" class="step-form" :colon="true" v-if="activeForm === 1" :data="formData1" @submit="onSubmit1"
        :rules="rules1" labelWidth="180px">
        <t-row>
          <t-col :span="12">
            <t-form-item name="background" label-align="top" label="研究背景">
              <tiny-mce-editor :key="activeForm" :maxlength="maxlength" :textLength.sync="lengthLimitObj.background"
                v-model="formData1.background"></tiny-mce-editor>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="text-align: center">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" @click="onCurChanged(0)">上一步</t-button>
              <t-button theme="primary" type="submit">下一步</t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
      <!-- 新增依托工程（项目）概述 -->
      <t-form ref="form" class="step-form" :colon="true" v-if="activeForm === 2" :data="formData2" @submit="onSubmit2"
        :rules="rules2" labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item name="projectOverview" label-align="top" label="依托工程（项目）概述">
              <tiny-mce-editor :key="activeForm" :maxlength="maxlength"
                :textLength.sync="lengthLimitObj.projectOverview" v-model="formData2.projectOverview"></tiny-mce-editor>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="text-align: center">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" @click="onCurChanged(1)">上一步</t-button>
              <t-button theme="primary" type="submit">下一步</t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
      <!-- 申报单位的前期工作和科研基础 -->
      <t-form ref="form" class="step-form" :colon="true" v-if="activeForm === 3" :data="formData3" @submit="onSubmit3"
        :rules="rules3" labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item name="workAndBasis" label-align="top" label="申报单位的前期工作和科研基础">
              <tiny-mce-editor :key="activeForm" :maxlength="maxlength" :textLength.sync="lengthLimitObj.workAndBasis"
                v-model="formData3.workAndBasis"></tiny-mce-editor>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="text-align: center">
          <t-col :span="12">
            <t-space :size="10">

              <t-button theme="primary" @click="onCurChanged(2)">上一步</t-button>
              <t-button theme="primary" type="submit">下一步</t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
      <t-form ref="form" class="step-form" label-align="top" :colon="true" v-if="activeForm === 4" :data="formData4"
        @submit="onSubmit4" :rules="rules4" labelWidth="180px">
        <t-form-item name="mainContent" label="主要内容">
          <tiny-mce-editor :key="activeForm" v-model="formData4.mainContent"></tiny-mce-editor>
        </t-form-item>
        <t-form-item name="scale" label="示范规模">
          <tiny-mce-editor :key="activeForm" v-model="formData4.scale"></tiny-mce-editor>
        </t-form-item>
        <t-form-item name="implementationPlan" label="组织实施方案">
          <tiny-mce-editor :key="activeForm" v-model="formData4.implementationPlan"></tiny-mce-editor>
        </t-form-item>
        <t-form-item :showErrorMessage="false" label-align="top" label="年度研究计划（包括起止年月、计划内容）" name="projectResearchPlan">
          <project-research-plan :disable-date="disableDate" ref="project-research-plan"
            v-model="formData4.projectResearchPlan" :projectId="getProjectId()" :editOpen="true"
            phaseType="1"></project-research-plan>
        </t-form-item>
        <t-row style="text-align: center">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" @click="onCurChanged(3)">上一步</t-button>
              <t-button theme="primary" type="submit">下一步</t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
      <!-- 推广技术的主要内容与规模 -->
      <t-form ref="form" class="step-form" :colon="true" v-if="activeForm === 5" :data="formData5" @submit="onSubmit5"
        :rules="rules5" labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item name="contentAndScale" label-align="top" label="推广技术的主要内容与规模">
              <tiny-mce-editor :key="activeForm" :maxlength="maxlength"
                :textLength.sync="lengthLimitObj.contentAndScale" v-model="formData5.contentAndScale"></tiny-mce-editor>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="text-align: center">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" @click="onCurChanged(4)">上一步</t-button>
              <t-button theme="primary" type="submit">下一步</t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
      <!-- 1.2.21.主要目标和成果形式 -->
      <t-form ref="form" class="step-form" :colon="true" v-if="activeForm === 6" :data="formData6" @submit="onSubmit6"
        :rules="rules6" labelWidth="180px" label-align="top">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item :showErrorMessage="false" name="goal" label="主要目标">
              <tiny-mce-editor v-model="formData6.goal"></tiny-mce-editor>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item :showErrorMessage="false" label="成果形式" name="projectExpectResults">
              <project-approach-expect-results phaseType="1" :projectId="getProjectId()"
                ref="project-approach-expect-results" v-model="formData6.projectExpectResults"
                :editOpen="true"></project-approach-expect-results>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="text-align: center">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" @click="onCurChanged(5)">上一步</t-button>
              <t-button theme="primary" type="submit">下一步</t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
      <!-- 单位信息 -->
      <t-form ref="form" class="step-form" :colon="true" v-if="activeForm === 7" :data="formData7" @submit="onSubmit7"
        :rules="rules7" labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item label="" name="unitList" label-align="top">
              <project-unit ref="project-unit" v-model="formData7.unitList" :adviceFunding="adviceFunding"
                :projectId="getProjectId()" :editOpen="true" phaseType="1"></project-unit>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row style="text-align: center">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" @click="onCurChanged(6)">上一步</t-button>
              <t-button theme="primary" type="submit">下一步</t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
      <t-form ref="form" class="step-form" :colon="true" v-if="activeForm === 8" :data="formData8" :rules="rules8"
        labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-table row-key="id" :columns="projectFileColumns" :data="projectFileData">
              <template #id="{ row, rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template #op="{ row }">
                <file-upload tips="限制pdf、图片" accept="application/pdf,image/*" v-model="row.fileIds"
                  :moduleKey="row.moduleKey" :fileList="row.fileLists" :multiple="true">
                  <t-button variant="outline">
                    <t-icon name="cloud-upload" slot="icon" />
                    点击上传
                  </t-button>
                </file-upload>
              </template>
              <template #c1="{ row }">
                <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1
                  }}</a>
                <div v-else>{{ row.c1 }}</div>
              </template>
            </t-table>
          </t-col>
        </t-row>
        <t-row style="text-align: center">
          <t-col :span="12">
            <t-space :size="10">
              <t-button theme="primary" @click="onCurChanged(7)">上一步</t-button>
              <t-button theme="primary" type="submit" @click="onSubmit8(1)">暂存</t-button>
              <!-- <t-tooltip content="提交后不可再编辑会进入审批流程">
            <t-button :disabled="isCommit" theme="primary" @click="onSubmit8(2)" type="submit">
              提交到单位管理员
            </t-button>
          </t-tooltip> -->
              <t-button :disabled="isCommit" theme="primary" @click="onSubmit8(2)" type="submit">
                提交
              </t-button>
            </t-space>
          </t-col>
        </t-row>
      </t-form>
    </div>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import ProjectUnit from "../project/components/project-unit.vue";
import ProjectResearchPlan from "../project/components/project-research-plan.vue";
import ProjectApproachExpectResults from "../project/components/project-approach-expectResults.vue";
import { TODAY } from '@/utils/date';
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";
import dayjs from "dayjs";
import FileUpload from "@/components/FileUpload/index.vue";
import { getFiles } from "@/api/common";

export default {
  name: "project-add",
  components: {
    TinyMceEditor,
    ProjectResearchPlan,
    ProjectApproachExpectResults,
    ProjectUnit,
    FileUpload
  },
  dicts: ["kjsf_key_word", "sys_user_sex", "prof_tit", "degree", "education", "duty"],
  data () {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,
      taskId: null,
      isCommit: false,
      projectFileData: [
        {
          id: 1,
          c1: "相关附件(包括依托工程或项目的立项审批、核准或备案证明材料等)",
          c2: "是",
          moduleKey: "projectLXSPZMCL",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        // {
        //   id: 2,
        //   c1: "核准或备案证明材料",
        //   c2: "是",
        //   moduleKey: "projectZMCL",
        //   fileIds: [],
        //   fileLists: [],
        //   require: true,
        // },
        {
          id: 3,
          c1: "其他",
          c2: "否",
          moduleKey: "projectQT",
          fileIds: [],
          fileLists: [],
          require: false,
        },
        // {
        //   id: 4,
        //   c1: "立项盖章文件",
        //   c2: "是",
        //   moduleKey: "projectYTGCCL",
        //   fileIds: [],
        //   fileLists: [],
        //   require: true,
        // },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      isSubmitNow: false,
      projectLeaderOptions: [],
      leaderLoading: false,
      adviceFunding: 0,
      profTitOptions: [],
      activeForm: 0,
      content: "",
      dictTypes: {},
      deptMenuOptions: [],
      applyLoading: false,
      maxlength: 500,
      lengthLimitObj: {
        description: 10,
        background: 500,
        contentAndScale: 500,
        workAndBasis: 500,
        projectOverview: 500,
        safeguardCondition: 2000
      },
      tinymceFlag: 1,
      current: 0,
      dayjs,
      projectLinkerOptions: [],
      projectLinkerOptions2: [],
      linkerLoading: false,
      linkerLoading2: false,
      formData0: {
        projectId: 0,
        projectLinker: {
          id: null,
          name: '',
          phone: '',
          email: '',
          postCode: '',
          address: '',
        },
        manageDeptLinker: {
          id: null,
          name: '',
          phone: '',
          email: '',
          postCode: '',
          address: '',
        },
        keyWordList: [],
        projectCompany: [],
        projectName: "",
        declareDate: TODAY,
        startDate: "",
        endDate: "",
        keyWord: '',
        adviceFunding: "",
        declareLinker: "",
        declarePhone: "",
        competentLinker: "",
        competentPhone: "",
        manageDeptName: "",
        manageDeptId: null,
        projectStatus: "1",
        projectLeader: {
          name: "",
          sex: "",
          birthDate: "",
          profTit: "",
          phone: "",
          address: "",
          email: "",
          postCode: "",
          school: "",
          majorName: "",
          degree: "",
          departmentId: null,
          idCard: "",
          education: "",
          majorNowName: "",
          duty: "",
          profTitId: null,
          task: ""
        }
      },
      // 增实施背景及必要性
      formData1: {
        background: ""
      },
      rules1: {
        background: [{ required: true, message: "实施背景及必要性不能为空" }],
      },
      rules7: {},
      rules8: {},
      // 新增依托工程（项目）概述
      formData2: {
        projectOverview: ""
      },
      rules2: {
        projectOverview: [{ required: true, message: "依托工程概述不能为空" }],
      },
      // 新增前期工作和科研基础
      formData3: {
        workAndBasis: ""
      },
      rules3: {
        workAndBasis: [{ required: true, message: "申报单位的前期工作和科研基础不能为空" }],
      },
      formData4: {
        mainContent: '',
        scale: '',
        implementationPlan: '',
        projectResearchPlan: [],
      },
      rules4: {
        mainContent: [{ required: true, message: "主要内容不能为空" }],
        scale: [{ required: true, message: "示范规模不能为空" }],
        implementationPlan: [{ required: true, message: "组织实施方案不能为空" }],
        projectResearchPlan: [
          { required: true, validator: (val) => val.length > 0, message: "年度研究计划不能为空", type: "error" }
        ],
      },
      // 推广技术的主要内容与规模
      formData5: {
        contentAndScale: "",
      },
      rules5: {
        contentAndScale: [{ required: true, message: "推广技术的主要内容与规模不能为空" }],
      },
      // 主要目标和成果形式
      formData6: {
        projectExpectResults: [],
        goal: '',
      },
      rules6: {
        goal: [{ required: true, message: "主要目标不能为空" }],
        projectExpectResults: [
          { required: true, validator: (val) => val.length > 0, message: "成果形式不能为空", type: "error" }
        ],
      },

      // 新增单位信息
      formData7: {
        unitList: []
      },
      formData8: {},
      rules0: {
        // //概述信息
        // background: [{ required: true, message: "研究背景不能为空!" }],
        //
        // //依托工程（项目）概述
        // projectOverview: [{ required: true, message: "依托工程（项目）概述不能为空!" }],
        //
        //
        // //1.2.13.前期工作和科研基础
        // workAndBasis: [{ required: true, message: "前期工作和科研基础不能为空!" }],
        //
        //
        // //推广技术的主要内容与规模
        // contentAndScale: [{ required: true, message: "推广技术的主要内容与规模不能为空!" }],

        // 1.2.21.主要目标和成果形式
        projectExpectResults: [
          { required: true, validator: (val) => val.length > 0, message: "预期研究成果及表达形式不能为空", type: "error" }
        ],


        // 1.2.23.单位信息
        unitList: [
          { required: true, validator: (val) => val.length > 0, message: "单位信息不能为空", type: "error" }
        ],

        // 其他需要说明的问题
        otherProblems: [{ required: true, message: "其他需要说明的问题不能为空!" }],

        projectCompany: [{ required: true, message: "项目合作（参与）单位不能为空" }],
        projectName: [{ required: true, message: "项目名称不能为空" }],
        declareDate: [{ required: true, message: "申报日期不能为空" }],
        manageDeptId: [{ required: true, message: "主管单位不能为空" }],
        startDate: [{ required: true, message: "项目开始日期不能为空" }],
        endDate: [
          {
            required: true,
            message: "项目结束时间不能为空",
          },
          {
            validator: (val) => {
              if (val && this.formData0.startDate) {
                const startTime = new Date(this.formData0.startDate).getTime()
                const endTime = new Date(val).getTime()
                return startTime <= endTime;
              }
              return true;
            }, message: "项目开始时间不能大于结束时间", type: "error"
          },
        ],
        adviceFunding: [
          {
            required: true,
            message: "投入经费（万元）不能为空",
          },
          {
            pattern: /^(0|([1-9]\d*))(\.\d+)?$/,
            message: "拟投入金额只能输入正数",
          },
        ],
        // adviceFunding: [{ required: true, message: "投入经费（万元）不能为空" }],

        goal: [{ required: true, message: "预期主要成果形式不能为空" }],
        mainContent: [{ required: true, message: "示范工程的主要内容、示范规模、进度安排和组织实施方案不能为空" }],
        declareLinker: [{ required: true, message: "申报单位联系人不能为空" }],
        declarePhone: [
          {
            required: true,
            message: "申报单位联系人电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "申报单位联系人电话请输入正确的手机号码",
          },
        ],
        keyWordList: [{ required: true, message: "关键字不能为空" }],
        competentLinker: [{ required: true, message: "主管单位联系人不能为空" }],
        competentPhone: [
          {
            required: true,
            message: "主管单位联系人电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "主管单位联系人电话请输入正确的手机号码",
          },
        ],

        projectStatus: [{ required: true, message: "项目状态不能为空" }],

        'manageDeptLinker.name': [
          {
            required: true,
            message: "主管部门联系人姓名不能为空",
          },
        ],
        'manageDeptLinker.phone': [
          {
            required: true,
            message: "主管部门联系人电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "主管部门联系人电话请输入正确的手机号码",
          },
        ],
        'manageDeptLinker.address': [
          {
            required: true,
            message: "主管部门联系人通讯地址不能为空",
          },
        ],
        'manageDeptLinker.email': [
          {
            required: true,
            message: "主管部门联系人邮箱不能为空",
          },
          { email: { ignore_max_length: true }, message: '请输入正确的邮箱地址' }
        ],
        'manageDeptLinker.postCode': [
          {
            required: true,
            message: "主管部门联系人邮编不能为空",
          },
        ],
        'projectLinker.name': [
          {
            required: true,
            message: "联系人姓名不能为空",
          },
        ],
        'projectLinker.phone': [
          {
            required: true,
            message: "联系人电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "联系人电话请输入正确的手机号码",
          },
        ],
        'projectLinker.address': [
          {
            required: true,
            message: "联系人通讯地址不能为空",
          },
        ],
        'projectLinker.email': [
          {
            required: true,
            message: "联系人邮箱不能为空",
          },
          { email: { ignore_max_length: true }, message: '请输入正确的邮箱地址' }
        ],
        'projectLinker.postCode': [
          {
            required: true,
            message: "联系人邮编不能为空",
          },
        ],


        "projectLeader.name": [{ required: true, message: "姓名不能为空" }],
        "projectLeader.sex": [{ required: true, message: "性别不能为空" }],
        'projectLeader.majorNowName': [
          {
            required: true,
            message: "项目主要负责人现从事专业不能为空",
          },
        ],
        'projectLeader.profTitId': [
          {
            required: true,
            message: "项目主要负责人技术职称不能为空",
          },
        ],
        'projectLeader.duty': [
          {
            required: true,
            message: "项目主要负责人职务不能为空",
          },
        ],
        'projectLeader.education': [
          {
            required: true,
            message: "项目主要负责人学历不能为空",
          },
        ],
        'projectLeader.task': [
          {
            required: true,
            message: "项目主要负责人在本项目中承担的任务不能为空",
          },
        ],
        "projectLeader.birthDate": [{ required: true, message: "出生日期不能为空" }],
        "projectLeader.profTit": [{ required: true, message: "职称不能为空" }],
        'projectLeader.idCard': [
          {
            required: true,
            message: "项目主要负责人身份证号不能为空",
          },
          {
            message: "项目主要负责人身份证号不正确",
            pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
        "projectLeader.phone": [
          {
            required: true,
            message: "联系人电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "联系人电话请输入正确的手机号码",
          },
        ],
        "projectLeader.address": [{ required: true, message: "通信地址不能为空" }],
        "projectLeader.email": [
          {
            required: true,
            message: "联系人邮箱不能为空",
          },
          { email: { ignore_max_length: true }, message: '请输入正确的邮箱地址' }
        ],
        "projectLeader.postCode": [{ required: true, message: "邮编不能为空" }],
        "projectLeader.school": [{ required: true, message: "毕业院校不能为空" }],
        "projectLeader.majorName": [{ required: true, message: "专业不能为空" }],
        "projectLeader.degree": [{ required: true, message: "学位不能为空" }],
        "projectLeader.departmentId": [{ required: true, message: "工作单位不能为空" }],
      },
      disableDate: {}
    }
  },
  watch: {
    activeForm: {
      immediate: true,
      handler (val) {
        const targetEle = document.getElementById("main")
        if (targetEle) {
          const { pos, top } = targetEle.style;
          targetEle.style.position = 'relative';
          targetEle.style.top = '-100px';
          targetEle.scrollIntoView({ behavior: 'smooth', block: 'start', inline: "nearest" });
          targetEle.style.top = top;
          targetEle.style.position = pos;
        }
      }
    }
  },
  async created () {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error("任务id丢失返回项目");
      this.$router.push("/kjsf/apply/project-my");
      return false;
    }
    await Promise.all([this.getDeptTreeSelect(),
    this.getProfTitTreeSelect()]);
    this.taskId = taskId;
    const activeForm = Number(sessionStorage.getItem(`${taskId}-activeForm`)) || 0;
    this.onCurChanged(activeForm, 0);
  },
  methods: {
    createProjectLeaderOptions (value) {
      this.projectLeaderOptions.push({
        label: `${value}`,
        value,
        name: value
      });
    },
    remoteProjectLeaderMethod (search) {
      this.leaderLoading = true;

      this.$api.system.member.searchList({ name: search }).then(response => {
        this.projectLeaderOptions = response.data.map(val => ({
          ...val,
          label: `${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.leaderLoading = false;
      }).catch((e) => {
        this.leaderLoading = false;
        this.$message.error(e.toString());
      });
    },
    onLeaderNameChange (val, content) {
      const index = this.projectLeaderOptions.findIndex(val => content?.option?.id === val.id)
      this.projectLeaderOptions[index].label = this.projectLeaderOptions[index].name;
      this.$set(this.projectLeaderOptions, index, this.projectLeaderOptions[index])
      // Object.assign(this.formData0.projectLeader, content.option)
      const oldId = this.formData0.projectLeader.id;
      this.$set(this.formData0, "projectLeader", this.projectLeaderOptions[index])
      this.formData0.projectLeader.id = oldId;
    },
    createProjectLinkerOptions (value) {
      this.projectLinkerOptions.push({
        label: `${value}`,
        value,
        name: value
      });
    },
    createProjectLinkerOptions2 (value) {
      this.projectLinkerOptions2.push({
        label: `${value}`,
        value,
        name: value
      });
    },
    onLinkerNameChange (val, content) {
      const index = this.projectLinkerOptions.findIndex(val => content.option?.id === val.id)
      this.projectLinkerOptions[index].label = this.projectLinkerOptions[index].name;
      this.$set(this.projectLinkerOptions, index, this.projectLinkerOptions[index])
      const oldId = this.formData0.projectLinker.id;
      this.$set(this.formData0, "projectLinker", this.projectLinkerOptions[index])
      this.formData0.projectLinker.id = oldId;
      // Object.assign(this.formData0.projectLinker,content.option)
    },
    onLinkerNameChange2 (val, content) {
      const index = this.projectLinkerOptions2.findIndex(val => content.option?.id === val.id)
      this.projectLinkerOptions2[index].label = this.projectLinkerOptions2[index].name;
      this.$set(this.projectLinkerOptions2, index, this.projectLinkerOptions2[index])
      const oldId = this.formData0.manageDeptLinker.id;
      this.$set(this.formData0, "manageDeptLinker", this.projectLinkerOptions2[index])
      this.formData0.manageDeptLinker.id = oldId;
      // Object.assign(this.formData0.projectLinker,content.option)
    },
    remoteProjectLinkerMethod (search) {
      this.linkerLoading = true;
      this.$api.system.member.searchList({ name: search }).then(response => {
        this.projectLinkerOptions = response.data.map(val => ({
          ...val,
          label: `${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.linkerLoading = false;
      }).catch((e) => {
        this.linkerLoading = false;
        this.$message.error(e.toString());
      });
    },
    remoteProjectLinkerMethod2 (search) {
      this.linkerLoading2 = true;
      this.$api.system.member.searchList({ name: search }).then(response => {
        this.projectLinkerOptions2 = response.data.map(val => ({
          ...val,
          label: `${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
        }));
        this.linkerLoading2 = false;
      }).catch((e) => {
        this.linkerLoading2 = false;
        this.$message.error(e.toString());
      });
    },
    createKeyWordOptions (value) {
      this.dict.type?.cg_key_word?.push({
        label: `${value}`,
        value,
      });
    },
    close () {
      this.applyLoading = false;
      setTimeout(() => {
        this.$tab.closeOpenPage({ path: this.$route.meta.activeMenu || "/kjsf/apply/project-my" });
      }, 1000)
    },
    getProjectId () {
      return sessionStorage.getItem(`${this.taskId}-step0`)
    },

    onProfTitIdChange (val, content) {
      this.formData0.projectLeader.profTit = content.node.data.level;
    },
    onCurChanged (cur, pre) {
      if (Number(cur) !== 0) {
        if (!sessionStorage.getItem(`${this.taskId}-step0`)) {
          this.applyLoading = false;
          this.$message.error("基本信息还未提交")
          return false;
        }
      }
      if (!this.applyLoading) {
        this.applyLoading = true;
      }
      // 根据不同的activeForm 复查数据
      if (Number(cur) === 0) {
        if (sessionStorage.getItem(`${this.taskId}-step0`)) {
          this.$api.kjsf.project.get(sessionStorage.getItem(`${this.taskId}-step0`)).then(response => {
            Object.assign(this.formData0, response.data)
            if (this.formData0.keyWord) {
              this.formData0.keyWordList = response.data.keyWord.split(",").filter(item => item !== '')
            }
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
            this.applyLoading = false;
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 1) {
        if (sessionStorage.getItem(`${this.taskId}-step1`)) {
          this.$api.kjsf.project.projectBackgroundDetailGetByProjectId(sessionStorage.getItem(`${this.taskId}-step0`)).then(response => {
            Object.assign(this.formData1, response.data)
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
            this.applyLoading = false;
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 2) {
        if (sessionStorage.getItem(`${this.taskId}-step2`)) {
          this.$api.kjsf.project.projectOverviewDetailGetByProjectId(sessionStorage.getItem(`${this.taskId}-step0`)).then(response => {
            Object.assign(this.formData2, response.data)
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
            this.applyLoading = false;
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 3) {
        if (sessionStorage.getItem(`${this.taskId}-step3`)) {
          this.$api.kjsf.project.projectWorkBasisDetailGetByProjectId(sessionStorage.getItem(`${this.taskId}-step0`)).then(response => {
            Object.assign(this.formData3, response.data)
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
            this.applyLoading = false;
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 4) {
        // 获取限制时间
        this.$api.kjsf.project.get(sessionStorage.getItem(`${this.taskId}-step0`)).then(pro => {
          if (pro.data) {
            this.disableDate = {
              before: dayjs(pro.data.startDate, "YYYY-MM-DD").endOf('month').subtract(1, 'month').format(),
              after: dayjs(pro.data.endDate, "YYYY-MM-DD").endOf('month').subtract(0, 'month').format(),
            }
          }
          if (sessionStorage.getItem(`${this.taskId}-step4`)) {
            this.$api.kjsf.project.projectMainContentGetByProjectId(sessionStorage.getItem(`${this.taskId}-step0`)).then(response => {
              Object.assign(this.formData4, response.data)
              this.activeForm = cur;
              sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
              this.applyLoading = false;
            }).catch(e => {
              this.applyLoading = false;
              this.$message.error(e.toString())
            })
          } else {
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
            this.applyLoading = false;
          }
        }).catch(e => {
          this.applyLoading = false;
          this.$message.error(e.toString())
        })
      } else if (Number(cur) === 5) {
        if (sessionStorage.getItem(`${this.taskId}-step5`)) {
          this.$api.kjsf.project.projectContentScaleDetailGetByProjectId(sessionStorage.getItem(`${this.taskId}-step0`)).then(response => {
            Object.assign(this.formData5, response.data)
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
            this.applyLoading = false;
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 6) {
        if (sessionStorage.getItem(`${this.taskId}-step6`)) {
          this.$api.kjsf.project.projectGoalGetByProjectId(sessionStorage.getItem(`${this.taskId}-step0`)).then(response => {
            Object.assign(this.formData6, response.data)
            this.activeForm = cur;
            sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
            this.applyLoading = false;
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }
      } else if (Number(cur) === 7) {
        this.activeForm = cur;
        sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
        this.applyLoading = false;
      } else if (Number(cur) === 8) {
        getFiles(sessionStorage.getItem(`${this.taskId}-step0`)).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          const fileLists = []
          this.projectFileData.forEach((val, index) => {
            this.projectFileData[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
            fileLists.push(...this.projectFileData[index].fileIds)
          })
          if (fileLists.length > 0) {
            sessionStorage.setItem(`${this.taskId}-step8`, res.data.length)
          }
          this.activeForm = cur;
          sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
          this.applyLoading = false;
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      }
      else {
        this.activeForm = cur;
        sessionStorage.setItem(`${this.taskId}-activeForm`, cur);
        this.applyLoading = false;
      }
    },
    isSubmit (name) {
      if (sessionStorage.getItem(`${this.taskId}-${name}`)) {
        return "已提交";
      }
      return "未提交";
    },
    getProfTitTreeSelect () {
      return this.$api.system.profTit.list().then(response => {
        // this.profTitOptions = response.data;
        this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getDeptTreeSelect () {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    filterByTree (val, tree, children = "children", id = "id", label = "label") {
      let text = '';
      const convert = (arr) => {
        arr.filter((item) => {
          if (item[id] === val) {
            text = item[label]
          } else if (item[children]) {
            return convert(item[children])
          }
          return false
        })
      }
      convert(tree)
      return text
    },
    onSubmit0 ({ validateResult, firstError }) {
      if (validateResult === true) {
        this.applyLoading = true;
        this.formData0.keyWord = this.formData0.keyWordList.join(",")
        // 判断是否提交过
        if (sessionStorage.getItem(`${this.taskId}-step0`)) {
          this.$api.kjsf.project.update(this.formData0).then(response => {
            this.$message.success("提交成功")
            this.onCurChanged(1);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {

          this.$api.kjsf.project.add(this.formData0).then(response => {
            this.$message.success("提交成功")
            sessionStorage.setItem(`${this.taskId}-step0`, response.data.id);
            this.onCurChanged(1);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        }
      } else {
        this.$message.error(firstError)
      }
    },
    onSubmit1 ({ validateResult, firstError }) {
      if (validateResult === true) {
        if (this.lengthLimitObj.background > this.maxlength) {
          this.$message.error(`研究背景： 当前字数：${this.lengthLimitObj.background}，限制字数：${this.maxlength}`)
          return false;
        }
        this.applyLoading = true;
        if (sessionStorage.getItem(`${this.taskId}-step1`)) {
          this.$api.kjsf.project.projectBackgrounUpdate({
            ...this.formData1,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            this.onCurChanged(2);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          // 获取到项目id后再提交添加请求
          this.$api.kjsf.project.projectBackgroundAdd({
            ...this.formData1,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            sessionStorage.setItem(`${this.taskId}-step1`, response.data.id);
            this.onCurChanged(2);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        }
      } else {
        this.$message.error(firstError)
      }

    },
    onSubmit2 ({ validateResult, firstError }) {
      if (validateResult === true) {
        if (this.lengthLimitObj.projectOverview > this.maxlength) {
          this.$message.error(`依托工程（项目）概述： 当前字数：${this.lengthLimitObj.projectOverview}，限制字数：${this.maxlength}`)
          return false;
        }
        this.applyLoading = true;
        if (sessionStorage.getItem(`${this.taskId}-step2`)) {
          this.$api.kjsf.project.projectOverviewUpdate({
            ...this.formData2,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            this.onCurChanged(3);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          // 获取到项目id后再提交添加请求
          this.$api.kjsf.project.projectOverviewAdd({
            ...this.formData2,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            sessionStorage.setItem(`${this.taskId}-step2`, response.data.id);
            this.onCurChanged(3);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        }
      } else {
        this.$message.error(firstError)
      }


    },
    onSubmit3 ({ validateResult, firstError }) {

      if (validateResult === true) {
        if (this.lengthLimitObj.workAndBasis > this.maxlength) {
          this.$message.error(`申报单位的前期工作和科研基础： 当前字数：${this.lengthLimitObj.workAndBasis}，限制字数：${this.maxlength}`)
          return false;
        }
        this.applyLoading = true;
        if (sessionStorage.getItem(`${this.taskId}-step3`)) {
          this.$api.kjsf.project.projectWorkBasisUpdate({
            ...this.formData3,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            this.onCurChanged(4);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          // 获取到项目id后再提交添加请求
          this.$api.kjsf.project.projectWorkBasisAdd({
            ...this.formData3,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            sessionStorage.setItem(`${this.taskId}-step3`, response.data.id);
            this.onCurChanged(4);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        }
      } else {
        this.$message.error(firstError)
      }

    },
    onSubmit4 ({ validateResult, firstError }) {

      if (validateResult === true) {
        // 年度研究计划 非空判断
        const isValidate = this.$refs["project-research-plan"].checkData()
        if (!isValidate) {
          return false;
        }
        if (sessionStorage.getItem(`${this.taskId}-step4`)) {
          this.$api.kjsf.project.projectMainContentUpdate({
            ...this.formData4,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            this.onCurChanged(5);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          // 获取到项目id后再提交添加请求
          this.$api.kjsf.project.projectMainContentAdd({
            ...this.formData4,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            sessionStorage.setItem(`${this.taskId}-step4`, response.data.id);
            this.onCurChanged(5);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        }
      } else {
        this.$message.error(firstError)
      }
    },
    onSubmit5 ({ validateResult, firstError }) {
      if (validateResult === true) {
        if (this.lengthLimitObj.contentAndScale > this.maxlength) {
          this.$message.error(`推广技术的主要内容与规模： 当前字数：${this.lengthLimitObj.contentAndScale}，限制字数：${this.maxlength}`)
          return false;
        }
        this.applyLoading = true;
        if (sessionStorage.getItem(`${this.taskId}-step5`)) {
          this.$api.kjsf.project.projectContentScaleUpdate({
            ...this.formData5,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            this.onCurChanged(6);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          this.$api.kjsf.project.projectContentScaleAdd({
            ...this.formData5,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            sessionStorage.setItem(`${this.taskId}-step5`, response.data.id);
            this.onCurChanged(6);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        }
      } else {
        this.$message.error(firstError)
      }


    },
    onSubmit6 ({ validateResult, firstError }) {

      if (validateResult === true) {

        const isValidate = this.$refs["project-approach-expect-results"].checkData()
        if (!isValidate) {
          return false;
        }
        if (sessionStorage.getItem(`${this.taskId}-step6`)) {
          this.$api.kjsf.project.projectGoalUpdate({
            ...this.formData6,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            this.onCurChanged(7);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        } else {
          this.$api.kjsf.project.projectGoalAdd({
            ...this.formData6,
            projectId: sessionStorage.getItem(`${this.taskId}-step0`)
          }).then(response => {
            this.$message.success("提交成功")
            sessionStorage.setItem(`${this.taskId}-step6`, response.data.id);
            this.onCurChanged(7);
          }).catch(e => {
            this.applyLoading = false;
            this.$message.error(e.toString())
          })
        }
      } else {
        this.$message.error(firstError)
      }

    },
    onSubmit7 ({ validateResult, firstError }) {
      if (validateResult === true) {
        const isValidate = this.$refs["project-unit"].checkData()
        if (!isValidate) {
          return false;
        }
        this.$api.kjsf.project.projectCompanyAddOrUpdate(this.formData7.unitList).then(response => {
          this.$message.success("提交成功")
          sessionStorage.setItem(`${this.taskId}-step7`, "1");
          this.onCurChanged(8);
        }).catch(e => {
          this.applyLoading = false;
          this.$message.error(e.toString())
        })
      } else {
        this.$message.error(firstError)
      }
    },
    onSubmit8 (type) {
      if (type === 1) {
        this.applyLoading = true;
        const sysAttMainIds = []
        this.projectFileData.forEach(val => {
          sysAttMainIds.push(...val.fileIds)
        })
        this.$api.kjsf.project.update({
          id: Number(sessionStorage.getItem(`${this.taskId}-step0`)),
          sysAttMainVo: {
            sysAttMainIds,
          }
        }).then(val => {
          sessionStorage.setItem(`${this.taskId}-fileId`, this.projectFileData.length);
          this.$message.success('暂存成功');
          this.applyLoading = false;
        }).catch((e) => {
          this.applyLoading = false;
          this.$message.error(e.toString());
        });
      } else {
        const isValidate = this.projectFileData.every(val => {
          if (val.require && val.fileIds.length <= 0) {
            this.$message.error(`需要上传${val.c1}`);
            return false;
          }
          return true
        })
        if (!isValidate) {
          return false
        }
        if (!sessionStorage.getItem(`${this.taskId}-step0`)) {
          this.$message.error("基本信息还未提交")
          this.applyLoading = false;
          return false;
        }
        if (!sessionStorage.getItem(`${this.taskId}-step1`)) {
          this.$message.error("实施背景及必要性还未提交")
          this.applyLoading = false;
          return false;
        }
        if (!sessionStorage.getItem(`${this.taskId}-step2`)) {
          this.$message.error("依托工程（项目）概述还未提交");
          this.applyLoading = false;
          return false;
        }
        if (!sessionStorage.getItem(`${this.taskId}-step3`)) {
          this.$message.error("申报单位的前期工作和科研基础还未提交");
          this.applyLoading = false;
          return false;
        }
        if (!sessionStorage.getItem(`${this.taskId}-step4`)) {
          this.$message.error("科技示范工程的主要内容、示范规模、进度安排和组织实施方案还未提交");
          this.applyLoading = false;
          return false;
        }
        if (!sessionStorage.getItem(`${this.taskId}-step5`)) {
          this.$message.error("推广技术的主要内容与规模还未提交");
          this.applyLoading = false;
          return false;
        }
        if (!sessionStorage.getItem(`${this.taskId}-step6`)) {
          this.$message.error("主要目标和成果形式还未提交");
          this.applyLoading = false;
          return false;
        }
        if (!sessionStorage.getItem(`${this.taskId}-step7`)) {
          this.$message.error("单位信息还未提交");
          this.applyLoading = false;
          return false;
        }
        this.applyLoading = true;
        this.isCommit = true;
        const sysAttMainIds = []
        this.projectFileData.forEach(val => {
          sysAttMainIds.push(...val.fileIds)
        })
        this.$api.kjsf.project.submit({
          id: Number(sessionStorage.getItem(`${this.taskId}-step0`)),
          sysAttMainVo: {
            sysAttMainIds
          }
        }).then(val => {
          sessionStorage.setItem(`${this.taskId}-fileId`, this.projectFileData.length);
          this.$message.success('提交成功');
          this.applyLoading = false;
          this.isCommit = false;
          this.close();
        }).catch((e) => {
          this.applyLoading = false;
          this.isCommit = false;
          this.$message.error(e.toString());
        });
      }
    }
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
